package DBNode

import (
	"strconv"
	"time"

	"git.oschina.net/yangdao/extlib/log"
	"git.oschina.net/yangdao/goerl"
	mgo "gopkg.in/mgo.v2-unstable"
)

var defaultDBNode *DBNode

//DBNode 数据节点负责数据的存储和读取
type DBNode struct {
	workNode *goerl.Node
}

//New 创建DBNode
func New() *DBNode {
	defaultDBNode = &DBNode{}
	defaultDBNode.workNode = goerl.NewNode(defaultDBNode.mailCenterHandler)
	<-goerl.Register("DBNode", defaultDBNode.workNode)
	return defaultDBNode
}

var db *mgo.Database

//Start 启动DBNode
func (dbNode *DBNode) Start() {
	dbNode.workNode.Start()

	sess, err := mgo.DialWithTimeout("localhost:27017", time.Second)
	if err != nil {
		log.Log("DBNode,Error", err)
		return
	}
	log.Log("DBNode,Info", "MongoDB数据库连接成功")
	db = sess.DB("ECDB")
}

func (dbNode *DBNode) mailCenterHandler(msg interface{}) {
	tuple := msg.([]interface{})
	msgHead := tuple[0].(string)
	switch msgHead {
	case ":req-register-login":
		deviceID := tuple[1].(string)
		sessID := tuple[2].(int64)
		account := accountQuery(deviceID)
		var err error
		if account == nil {
			log.Log("query" + deviceID + "fail")
			account, err = accountRegister(deviceID, "游客"+strconv.Itoa(time.Now().Second()))
			if err != nil {
				log.Log("DBNode,Error", err)
			}
		}
		goerl.SendByName("LobbyNode", []interface{}{":DBMail", ":res-register-login", deviceID, account.NickName, account.Level, sessID, deviceID})
	}
}
